<?php
namespace app\user\controller;
use think\Db;
use EasyWeChat\Foundation\Application;
use EasyWeChat\Payment\Order;
use mlsmt\Cabinet\Send;
class Leaseorder extends Common
{
    /**
     *todo 获取充电宝价格,需要修改价格
     *
     */
    public function getprice()
    {
        $oid = 1;
        $cid = input('param.cid');
        if(!$oid){
            $info['code']=0;
            $info['msg'] = '没有运营商信息';
            return $info;
        }
        if(!$cid){
            $info['code']=0;
            $info['msg'] = '没有机柜信息';
            return $info;
        }
    	//获取价格详情
    	$price = Db::name('operator')
            ->where('id',$oid)
            ->field('id,deposit,amount,billingunit,billingtime,freetime,ceiling')
    		->find();
        if(!$price){
            $info['code']=0;
            $info['msg'] = '价格信息异常！';
            return $info;
        }
        $seller =  Db::name('charecabinet')
            ->where('cabinet_id',$cid)
            ->where('is_delete',1)
            ->field('sid')
            ->find();
        if(!$seller || !$seller['sid']){
            $info['code']=0;
            $info['msg'] = '机柜信息未添加或未绑定商户！';
            return $info;
        }

        $sellerInfo = Db::name('seller')
            ->field('per_price,id')
            ->where(['id' => $seller['sid'], 'status' => 1])
            ->find();
        if (!$sellerInfo) {
            $info['code']=0;
            $info['msg'] = '机柜信息未添加或未绑定商户！';
            return $info;
        }
        $info['price'] = $sellerInfo['per_price'] ? $sellerInfo['per_price'] : $price;
        $info['seller'] = $seller;
        $info['code']=1;
        return $info;
    }

    /**
     *获取订单详情
     *
     */
    public function getleaseorder(){
        $oid = 1;
        $openid = mwdecrypt(input('param.openid'));
        $orderid = input('param.orderid');

        //获取运营商价格
        $info['operator'] = Db::name('operator')
            ->where('id',$oid)
            ->field('amount,billingunit,billingtime,freetime,ceiling')
            ->find();
        //获取订单详情
        $info['leaseorder'] = Db::name('leaseorder')
            ->where('oid',$oid)
            ->where('id',$orderid)
            ->find();
        return $info;

    }

    /**
     *接口返回开始租赁,判断一些条件
     *
     *
     */
    public function startlease()
    {
        $oid = 1;//测试用41
        $openid = mwdecrypt(input('param.openid'));
        $sid = input('param.sid');
        $formid = input('param.formid');
        $cabinetid = input('param.cabinetid');//机柜号

        //判断当前用户余额是否大于0，押金是否够设定的押金
        $user = Db::name('user')->where('oid',$oid)->where('openid',$openid)->field('id,balance,deposit,mobile')->find();
        $operator = Db::name('operator')->where('id',$oid)->find();

        //获取是否需要绑定手机,如果没有绑定手机，先跳到绑定手机也没
        if ($operator['bindmobile'] && empty($user['mobile'])) {
            $res['code'] = 6;
            $res['info'] = '清先绑定用户手机';
            return $res;
        }

        if ($operator['deposit'] >=0 && $user['deposit'] < $operator['deposit']) {
             $res['code'] = 9;
            //$res['info'] = '余额或押金不足';
            $res['info'] = '请先缴纳押金';
            return $res;
        }


        if ($user['balance'] <= 0 ) {
            if ($operator['deposit'] <= 0 ) {//不需要缴纳押金
                $res['code'] = 7;
            } else {
                $res['code'] = 8;
            }
            //$res['info'] = '余额或押金不足';
            $res['info'] = '余额不足，请先充值';
            return $res;
        }

        //查询当前是否未归还订单存在
        $leaseorder = Db::name('leaseorder')
            ->where('oid',$oid)
            ->where('uid',$user['id'])
            ->where('endtime',NULL)
            ->where('status','NEQ',2)
            ->where('is_delete',1)
            ->find();

        if($leaseorder){
            $res['code'] = 2;
            $res['info'] = '当前有正在租赁的订单！';
            $res['orderid'] = $leaseorder['id'];
            return $res;

        }else{
            //执行弹出充电宝指令。
            $Send = new Send($cabinetid);
            $status = $Send->BorrowDevice();

            //判断是否弹出成功
            if($status['types']==1){
                
                $seller =  Db::name('seller')->where('id',$sid)->where('oid',$oid)->field('name')->find();
                //将数据添加到数据库
                $data = array(
                    'oid' => $oid, 
                    'sid' => $sid, 
                    'uid' => $user['id'], 
                    'formid' => $formid,
                    'order_no' => '501' . date('ymdHis') . rand(1000, 9999),
                    'name' => '租借'.$seller['name'].'充电宝', 
                    'starttime' => time(), 
                    'status' => 1, 
                    'deviceid' => $status['info'],
                    'cabinetid' => $cabinetid, 
                    'create_time' => time(),
                );
                Db::name('leaseorder')->insert($data);
                $orderid = Db::name('leaseorder')->getLastInsID();
                $res['code'] = 1;
                $res['info'] = '租借成功！';
                $res['cabinetid'] = $cabinetid;
                $res['deviceid'] = $status['info'];
                $res['orderid'] = $orderid;
                return $res;
            }elseif($status['types']==2){
                $res['code'] = 3;
                $res['info'] = '弹出失败，请重新扫码！';
                return $res;
            }elseif($status['types']==3){
                $res['code'] = 4;
                $res['info'] = '充电宝被借完啦,晚点再来看看吧。';
                return $res;
            }elseif($status['types']==4){
                $res['code'] = 4;
                $res['info'] = '充电宝电量不足，请稍后再试.';
                return $res;
            }else{
                $res['code'] = 5;
                $res['info'] = '此机柜没有中国移动网络信号，请重新开机，然后扫二维码.';
                $res['res'] = $status;
                return $res;
            }
        }

    }
    //获取订单状态
    public function getstatus(){

        $oid = 1;
        $orderid = input('param.orderid');

        $res['info'] = Db::name('leaseorder')
            ->where('oid',$oid)
            ->where('id',$orderid)
            ->find();
        if($res['info']['status']==2){
            $res['code'] = 1;
        }else{
            $res['code'] = 0;
        }
        return $res;


    }
    //获取订单详情
    public function leaseorderinfo()
    {
        $oid = 1;
        $openid = mwdecrypt(input('param.openid'));
        $orderid = input('param.orderid');

        
        //获取订单详情
        $info['leaseorder'] = Db::name('leaseorder')
            ->where('oid',$oid)
            ->where('id',$orderid)
            ->find();
        if($info['leaseorder']){
            //商户详情
            $seller = Db::name('seller')
                ->where('id',$info['leaseorder']['sid'])
                ->field('name')
                ->find();
            $info['leaseorder']['sellername'] = $seller['name'];

        }

        return $info;
        

    }


    //归还
    public function return_device($deviceid)
    {
        //save_log('../','');
        //获取订单详情
        $leaseorder = Db::name('leaseorder')
            ->where('deviceid',$deviceid)
            ->where('status',1)
            ->find();

        $oid = $leaseorder['oid'];
        $uid = $leaseorder['uid'];
        $orderid = $leaseorder['id'];

        //获取运营商价格
        $operator = Db::name('operator')
            ->where('id',$oid)
            ->cache(true)
            ->find();

        $operator['billingunit']==1?$arithmetical = 3600:$arithmetical = 60;

        $time = time();
        $billingunit =  ceil(($time - $leaseorder['starttime'])/($arithmetical * $operator['billingtime']));
        $amount = $billingunit * $operator['amount'];

        $data = array(
            'endtime' => $time, 
            'billingunit' => $billingunit, 
            'amount' => $amount, 
            'status' => 2, 
            'payable_amount' => $amount, 
            'real_amount' => $amount, 
            
        );
        Db::name('leaseorder')->where('oid',$oid)->where('id',$orderid)->update($data);
        Db::name('user')->where('oid',$oid)->where('id',$uid)->setDec('balance', $amount);
    }

    //获取订单列表
    public function leaseorderlist()
    {
        $oid = 1;
        $openid = mwdecrypt(input('param.openid'));

        $user =  Db::name('user')->where('oid',$oid)->where('openid',$openid)->field('id')->find();

        //获取订单列表
        $info['leaseorder'] = Db::name('leaseorder')
            ->where('oid',$oid)
            ->where('uid',$user['id'])
            ->select();
        if($info['leaseorder']){
            foreach ($info['leaseorder'] as $key => $value) {
               
                $info['leaseorder'][$key]['date'] = date("Y-m-d H:i:s",$value['starttime']);
                    
            }

            return $info;
        }else{
            return '';
        }
    }

}
